<?php


namespace App\Http\Controllers\Front;


use App\Http\Controllers\Controller;
use App\Model\Cards;
use App\Model\UserDetail;
use App\Model\UserMsg;
use App\Model\WeChat;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class MaiBaoController extends Controller
{
    /**
     * @var \App\User
     */
    private $user;

    public function __construct()
    {
        $this->user = Auth::user();
    }

    public function index()
    {
        return $this->renderJson(['maibao' => intval($this->user->maibao)]);
    }

    public function bill()
    {
        $m = DB::table('maibao_bill as mb')->select('mb.id','mb.user_id','mb.title','mb.amount','mb.cate','mb.created_at','mbe.from_id', 'c.head_picture')->leftJoin('maibao_bill_extend as mbe', 'mbe.bill_id', '=', 'mb.id')
            ->leftJoin('cards as c', 'c.user_id','=', 'mbe.from_id')
            ->where('mb.user_id', $this->user->id);
        if (request()->route()->getName() == 'maibao.income') {
            $m->where('mb.type', 1);
        } elseif (request()->route()->getName() == 'maibao.expenditure') {
            $m->where('mb.type', -1);
        }
        $res = $m->orderByDesc('mb.created_at')->paginate(request('limit', 10));
        return $this->renderJson($res);
    }

    /**
     * 朋友列表(我收藏对方名片同时对方收藏我名片)
     * @return \Illuminate\Http\Response
     */
    public function friend()
    {
        $card = Cards::where('user_id', $this->user->id)->first();
        if (!$card) {
            return $this->renderJson([]);
        }
        $cards = DB::table('cards')->select('user_name', 'user_id', 'id', 'head_picture', 'motto', 'industry', 'company', 'profession', 'created_at')->whereIn('user_id', function ($query) {
            $query->select('user_id')
                ->from('card_holders')
                ->whereIn('user_id', function ($query) {
                    $query->select('user_id')
                        ->from('cards')
                        ->whereIn('id', function ($query) {
                            $query->select('card_id')
                                ->from('card_holders')
                                ->where('user_id', $this->user->id);
                        });
                });
        })->get();
        $users = $cards->pluck('user_id');
        $vip = DB::table('user_grade')->whereIn('user_id', $users)->where('overed_at', '>', Carbon::now())->pluck('user_id');
        $v = Cache::get('maibao_remind');
        foreach ($cards as &$card) {
            $card->is_vip = false;
            $card->is_remind = false;
            if (in_array($card->user_id, $vip->toArray())) {
                $card->is_vip = true;
            }
            if (in_array(md5("maibao_remind-{$this->user->id}-{$card->user_id}"),$v)) {
                $card->is_remind = true;
            }
        }
        return $this->renderJson($cards);
    }

    /**
     * 赠送
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function give(Request $request, $id)
    {
        $this->validate($request, [
            'amount' => 'required|numeric'
        ], [
            'amount.required' => '金额不能为空',
            'amount.numeric' => '金额必须是数字'
        ]);
        $amount = $request->input('amount');
        if ($amount <= 0) {
            return $this->fail('金额错误');
        }
        //对方是否是双方关注
        $r = DB::table('cards')->whereIn('id', function ($query) {
            $query->select('card_id')
                ->from('card_holders')
                ->where('user_id', $this->user->id);
        })->where('user_id', $id)->first();
        if (is_null($r)) {
            return $this->fail('对方不在你好友或者你不是对方好友');
        }
        if (!DB::table('user_grade')->where('user_id', $id)->where('overed_at', '>', Carbon::now())->first()){
        	return $this->fail('对方还不是会员，你不能赠送给TA哦');
        }
        //自己的余额
        if (User::find($this->user->id)->maibao < $amount) {
            return $this->fail('余脉宝不足');
        }
        //转账
        try {
            DB::beginTransaction();
            $from = User::where('id', $this->user->id)->lockForUpdate()->first();
            $to = User::where('id', $id)->lockForUpdate()->first();
            if (is_null($from) || is_null($to)) {
                DB::rollBack();
                return $this->fail('用户不存在');
            }
            if ($from->maibao < $amount) {
                DB::rollBack();
                return $this->fail('余脉宝不足');
            }
            //用户转出
            $from->decrement('maibao', $amount);
            $from->save();
            //日志
            $bill_id = DB::table('maibao_bill')->insertGetId([
                'user_id' => $this->user->id,
                'type' => -1,
                'title' => '赠送给 ' . $r->user_name,
                'amount' => $amount,
                'cate' => 2,
                'created_at' => Carbon::now()
            ]);
            DB::table('maibao_bill_extend')->insert([
                'type' => 2,
                'user_id' => $id,
                'bill_id' => $bill_id,
                'from_id' => $this->user->id,
                'created_at' => Carbon::now()
            ]);
            //目标收入
            $to->increment('maibao', $amount);
            $to->save();
            //日志
            $bill_id2 = DB::table('maibao_bill')->insertGetId([
                'user_id' => $id,
                'type' => 1,
                'title' => $this->user->cards->user_name . ' 赠送给我',
                'amount' => $amount,
                'cate' => 2,
                'created_at' => Carbon::now()
            ]);
            DB::table('maibao_bill_extend')->insert([
                'type' => 2,
                'user_id' => $this->user->id,
                'bill_id' => $bill_id2,
                'from_id' => $id,
                'created_at' => Carbon::now()
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('系统错误');
        }
        return $this->success();
    }

    public function goods()
    {
        return $this->renderJson(DB::table('maibao_goods')->get());
    }

    public function remind($id)
    {
        $key = md5("maibao_remind-{$this->user->id}-{$id}");
        $v = Cache::get('maibao_remind')?:[];
        if (in_array($key, $v)){
            return $this->fail('你已经提醒过了');
        }
        $userDetail = UserDetail::where('user_id', $id)->first();
		UserMsg::add("送脉宝",User::getUserName($this->user->id)."要赠送给您脉宝，快去开通会员接受馈赠！",UserMsg::MAIBAO,$this->user->id,$id);
		//提醒
        WeChat::sendWeChatMsg($userDetail->open_id, env('WECHAT_TEMPLATE_ID_MAIBAO'), env('MAIBAO_URL'),[
            'first' => '充值会员消息',
            'keyword1' => $this->user->detail->wechat_name . ' 邀请你享受高级营销权限，快去开通会员吧！',
            'keyword2' => Carbon::now()->toDateString(),
            'remark' => '点击查看详情'
        ]);
        array_push($v, $key);
        Cache::put('maibao_remind', $v);
        return $this->success();
    }

}